<template>
  <view class="m-date">
    <view v-if="visible" class="mask-layer" @tap="$emit('update:visible', false)" />
    <u-transition class="m-data-picker" mode="slide-up" :show="visible">
      <view class="btn">
        <view class="cancel" @tap="cancel">取消</view>
        <view class="confirm" @tap="confirm">确定</view>
      </view>
      <picker-view :indicator-style="indicatorStyle" :value="dateValue" @change="bindChange">
        <picker-view-column>
          <view v-for="(item, index) in years" :key="index" class="item">
            {{ item }}
          </view>
        </picker-view-column>
        <picker-view-column>
          <view v-for="(item, index) in months" :key="index" class="item">
            {{ item }}
          </view>
        </picker-view-column>
        <template v-if="type !== 'month'">
          <picker-view-column>
            <view v-for="(item, index) in days" :key="index" class="item">
              {{ item }}
            </view>
          </picker-view-column>
          <template v-if="type === 'datetime'">
            <picker-view-column>
              <view v-for="(item, index) in hours" :key="index" class="item">
                {{ item }}
              </view>
            </picker-view-column>
            <picker-view-column>
              <view v-for="(item, key) in minutes" :key="key" class="item">
                {{ item }}
              </view>
            </picker-view-column>
          </template>
        </template>
      </picker-view>
    </u-transition>
  </view>
</template>
<script setup lang="ts" name="">
import dayjs from "dayjs";
import { minutes, indicatorStyle, hours, months } from "./hooks/constant";

export interface MDatePickerProp {
  dValue: string;
  visible?: boolean;
  minYear?: number;
  type?: "date" | "datetime" | "month";
}

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<MDatePickerProp>(), {
  dValue: "",
  visible: false,
  minYear: 10,
  type: "datetime"
});
const $emit = defineEmits(["update:visible", "update:dValue", "confirm", "cancel"]);
let dateValue = ref<any>([]);
// 年
let years = ref([]);
// 天
let days = ref([]);

watch(
  () => props.visible,
  flag => {
    if (flag) init();
  }
);

// 初始化
const init = () => {
  let date;
  if (props.dValue) {
    date = dayjs(props.dValue).format("YYYY-MM-DD-HH-mm");
  } else {
    date = dayjs().format("YYYY-MM-DD-HH-mm");
  }
  const d = date.split("-");
  // 获取年份
  getYears();

  // 获取接近分钟
  const mKey = getMinute(parseInt(d[4]) - 1);

  dateValue.value = [props.minYear - 1, parseInt(d[1]) - 1, parseInt(d[2]) - 1, parseInt(d[3]), mKey];

  // 设置天数
  days.value = setDays();
};

// 确定
const confirm = () => {
  getTime();
  $emit("update:visible", false);
  $emit("confirm");
};
// 取消
const cancel = () => {
  $emit("update:visible", false);
  $emit("cancel");
};
const bindChange = e => {
  const val = e.detail.value;
  dateValue.value = val;
  // 重新获取天数
  days.value = setDays();
};
// 获取当前时间
const getTime = () => {
  // 年
  const year = years.value[dateValue.value[0]];
  // 月
  const month = months[dateValue.value[1]];
  // 日
  const day = days.value[dateValue.value[2]];
  // 时
  const hour = hours[dateValue.value[3]];
  // 分
  const minute = minutes[dateValue.value[4]];

  let str = `${year}-${month}-${day}`;
  if (props.type === "datetime") {
    str += ` ${hour}:${minute}`;
  }
  if (props.type === "month") {
    str = `${year}-${month}`;
  }

  $emit("update:dValue", str);
};

// 设置时
const setDays = () => {
  const year = years.value[dateValue.value[0]];
  const month = months[dateValue.value[1]];
  const days = dayjs(`${year}-${month}`).daysInMonth();
  const s = [];
  for (let i = 1; i <= days; i++) {
    s.push(i < 10 ? "0" + i : i + "");
  }
  return s;
};

// 获取分
const getMinute = m => {
  const minute = m;
  if (m <= 8) {
    return 0;
  } else if (m > 8 && m <= 23) {
    return 1;
  } else if (m > 23 && m <= 37) {
    return 2;
  } else if (m > 37) {
    return 3;
  }

  return minute;
};

// 获取年
const getYears = () => {
  // 当前年
  const presentYears = parseInt(dayjs().format("YYYY"));
  years.value = [];
  for (let i = 0; i < props.minYear; i++) {
    years.value.unshift(presentYears - i);
  }
};
</script>
<style lang="scss" scoped src="./index.scss"></style>
